import requests
from fastapi.responses import JSONResponse
from fastapi import Response

class ZaobaoAPI:
    def __init__(self):
        self.zaobao = 'zaobao'
    def handle(self, type):
        response = requests.get('https://xzdx.top/api/zaobao/')
        data = response.json()
        if data["data"]:
            if type == 'json':
                resData = {
                    "code": 200,
                    "msg": "success",
                    "method": "GET",
                    "data": data["data"],
                    "ip": data["ip"],
                    "date": data["date"],
                }
                return JSONResponse(resData, status_code=200, headers={"Content-Type": "application/json, charset=utf-8"})
            elif type == "image":
                image_url = data["data"]["image"]
                if image_url:
                    response = requests.get(image_url)
                    return Response(content=response.content, media_type="image/jpeg")
                else:
                    return Response(content="图片不存在", media_type="text/plain, charset=utf-8")
            else:
                return JSONResponse(
                    content={"error": "请求参数错误", "code": 3},
                    status_code=200,
                    media_type="application/json; charset=utf-8"
                )    
        else:
            return Response(content="获取数据失败，接口地址可能已经失效", media_type="text/plain, charset=utf-8")